<?php

namespace app\common\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{
    use SoftDelete;



    // 表名
    protected $name = 'goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }


    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function goodsList($param)
    {
        extract($param);
        $where=['enddate'=>['>',time()],'status'=>1];
      $district ='';
        $area_id=0;

        $where2=[];
        if (!empty($district)){
            $district_id=db('marea')->where(['name'=>$district,'level'=>3])->value('id');
            $area_id=$district_id;
            $where2[] = ['exp', Db::raw("FIND_IN_SET($area_id,area_ids)")];
//
            $data =$this->where($where)
                ->where('find_in_set(:id,area_ids)', ['id' => $area_id])
                ->order(['weigh'=>'desc'])->paginate();
        }else{
            $data =$this->where($where)->order(['weigh'=>'desc'])->paginate();
        }


        foreach ($data as $k=>$v){
            $v['goods_image'] =cdnurl($v['goods_image'],true);
            $v['goods_images']=explode(',',$v['goods_images']);
            $goods_images=[];
            foreach ($v['goods_images'] as $k1=>$v1){
                $goods_images[]=cdnurl($v1,true);
            }
            $v['goods_images']=$goods_images;
            $v['goods_sales'] =$v['goods_sales']+$v['base_sales'];
            unset($v['base_sales']);
        }
        return $data;
    }


}
